<template>
    <div>
        <!-- 首页头部 -->
        <div class="home-header">
            <div class="home-logo">
                <i class="fas fa-newspaper"></i>
                <span>万象新讯</span>
            </div>
            <div class="home-actions">
                <el-badge :value="unReadMsg" :hidden="unReadMsg===0" class="item" type="primary">
                    <div @click="navigateTo('/Notifications')"><i class="fas fa-bell"></i></div>
                </el-badge>
                <div @click="navigateTo('/Settings')"><i class="fas fa-cog"></i></div>
            </div>
        </div>

        <!-- 分类标签 -->
        <div class="category-tags">
            <div v-for="(tag, index) in newsCategoryArr" :key="tag.id" class="category-tag"
                :class="{ active: activeTag === tag.id }" @click="selectTag(tag)">
                {{ tag.name }}
            </div>
        </div>

        <!--占位-->
        <div class="top-bar"></div>

        <!-- 内容区域 -->
        <div v-if="activeTag==0" class="contentBox" ref="contentContainer" 
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
        >
        <!-- 下拉刷新指示器 -->
        <div v-if="isRefreshing==false" class="refresh-hint" :style="{ transform: `translateY(${translateY}px)` }">
            
                <span v-if="translateY != 0" class="pull-hint">
                    <i style="display: flex;flex-direction: column;justify-content: center;" class="fas fa-arrow-down"></i>
                    <p>下拉刷新</p>
                </span>
                <span v-else class="pull-hint">
                    <i style="display: flex;flex-direction: column;justify-content: center;" class="fas fa-arrow-up"></i>
                    <p>松开刷新</p>
                </span>
           
        </div>
        <div v-if="isRefreshing==true && isPull==false" class="refresh-hint">
            <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>正在刷新...</span>
            </div>
        </div>

            <!-- 头条新闻 -->
            <div class="featured-news">
                <div class="section-title">头条新闻</div>
                <div class="card" @click="navigateToNewsDetails(newsList[0])">
                    <img v-if="newsList[0]?.frontCover" :src="newsList[0]?.frontCover"
                        class="card-image" alt="头条新闻">
                    <div class="card-content">
                        <div class="card-title">{{ newsList[0]?.title }}</div>
                        <div class="card-meta">
                            <div>头条 · {{ getNewsCategoriesName(newsList[0]?.categoryId) }}</div>
                            <div>{{ formatTimeAgo(newsList[0]?.publishTime) }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 热门新闻 -->
            <div class="section-title">热门推荐</div>
            <div class="news-list">
                <div v-for="(news, index) in newsList.slice(1)" :key="index"
                    :class="[{ 'card': news.type !== 'list-item', 'list-item': news.type === 'list-item' }]"
                    @click="navigateToNewsDetails(news)">
                    <div >
                        <img v-if="news.frontCover" :src="news.frontCover"
                            :class="['card-image', { 'list-item-image': news.type === 'list-item' }]" :alt="news.title"
                            :style="{ borderRadius: news.type === 'list-item' ? '6px' : '0', objectFit: news.type === 'list-item' ? 'cover' : 'unset' }"
                        >
                    </div>
                    <div class="card-content" style="width: 100%;">
                        <div :class="[{ 'card-title': news.type !== 'list-item', 'list-item-title': news.type === 'list-item' }]">
                            {{ news.title }}
                        </div>
                        <div class="card-meta">
                            <div>{{ getNewsCategoriesName(news.categoryId) }}</div>
                            <div>{{ formatTimeAgo(news.publishTime) }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载更多 -->
            <!-- <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span style="margin-left: 8px;">正在加载更多...</span>
            </div> -->
        </div>

        <div v-else class="contentBox">
            <NewsList :category-id="activeTag.toString()"/>
        </div>
        

        <div class="foot-bar"></div>
        <Foot activeIcon="Home"/>
    </div>
</template>

<script lang="ts" setup>
import { ref,computed, onMounted, onActivated, onDeactivated } from 'vue';
import Foot from '@/components/Foot.vue';
import api from '@/api';
import { useRouter,useRoute,onBeforeRouteLeave  } from 'vue-router';
import NewsList from '@/components/NewsList.vue';
import { UserStore } from '@/stores/userInfoStore';
import { NewsStore } from '@/stores/newsInfoStore';


const route = useRoute();
const router = useRouter();
const userStoreObject = UserStore();
const newsStoreObject = NewsStore();



//#region 头部分类标签
const activeTag = ref(0)
const newsCategoryArr = ref([
    { id: 0, name: '推荐' },
])

const selectTag = (tag) => {
    activeTag.value = tag.id;
};


//#endregion


//#region 热门推荐
const newsList = ref([])
//加载新闻
const simulateLoading = async() => {
    await api.pushNews(userStoreObject.userInfo.id).then((res) => {
        if(res.data.code == 1){
            newsList.value = res.data.data
        }else{
            console.log("获取新闻失败")
        }
        console.log(res)
    }).catch((err) => {
        console.error(err)
    })

    // 为接收到的对象数组添加属性
    newsList.value.forEach((item, index) => {
        if (item.frontCover === null || item.frontCover === "") { // 如果 封面 为 null 或者为空字符串，设置 type 为 list-item
            item.type = "list-item";
        } else if (index % 3 === 0) { // 每隔三个元素的第一个为 card
            item.type = "card";
        } else {
            item.type = "list-item";
        }
    });

};

// 获取新闻分类名称
const getNewsCategoriesName = (Id) => {
    if (Id != null) {
        return newsStoreObject.newsCategoryInfo.find(ncInfo => ncInfo.id == Id)?.name;
    } else { return null }
};

//#endregion



//#region 定义方法
function formatTimeAgo(timeStr) {
    // 将传入的时间字符串转换为 Date 对象
    const time = new Date(timeStr);
    // 获取当前时间
    const now = new Date();
    // 计算时间差（单位：毫秒）
    const diff = now.getTime() - time.getTime();

    // 将时间差转换为分钟、小时、天
    const minutes = Math.floor(diff / 1000 / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    // 根据时间差返回对应的时间格式
    if (days > 7) {
        return "7天前";
    } else if (days > 0) {
        return `${days}天前`;
    } else if (hours > 0) {
        return `${hours}小时前`;
    } else if (minutes > 0) {
        return `${minutes}分钟前`;
    } else {
        return "刚刚";
    }
}

// 跳转
const navigateTo = (url: string) => {
    router.push({ path: url});
};

// 跳转文章详情页
const navigateToNewsDetails = (news) => {
    router.push({
        path: '/NewsDetails',
        query: { 
            NewsId: news.id,
            newsCategoryName: getNewsCategoriesName(news.categoryId)
        }
    });
};

//获取未读消息
const unReadMsg = ref(0);
const getUnreadNotice = async() => {
    let res = await api.getNoticeByUserId(userStoreObject.userInfo.id);
    unReadMsg.value = res.data.data.list.filter(item => item.isRead === false).length;
};

//#endregion



//#region 下拉刷新
const contentContainer = ref();
const isPull = ref(false); // 是否正在下拉（特指在顶部时候的下拉）
const isPush = ref(false); // 是否正在上滑
const isRefreshing = ref(false); // 是否正在刷新

let startY = 0; // 触摸起始点的 Y 坐标
let endY = 0; // 触摸结束点的 Y 坐标
const translateY = ref(-40); // 初始偏移量

// 触摸开始
function handleTouchStart(event){
    startY = event.touches[0].clientY;
    //console.log("起始Y值:",startY)
}

// 触摸移动
function handleTouchMove(event){
    
    //触摸还没结束并且正在下拉的时候阻止滚动事件
    if(endY == 0 && isPull.value == true){
        // 阻止滚动事件，避免页面滚动（使用户可以通过上滑取消本次刷新）
        contentContainer.value.style.overflow='hidden'; 
    }
    //只有滚动条在顶部的时候才执行下面的逻辑
    //console.log("滚动条Y值:",contentContainer.value.scrollTop)
    if(contentContainer.value.scrollTop != 0){
        return;
    }

    // 获取触摸移动时的 Y 坐标
    const currentY = event.touches[0].clientY;
    const deltaY = currentY - startY;
    // 下滑才执行
    if(deltaY > 0){
        isPull.value = true;
        const pullRatio = Math.min(deltaY  / 100, 1) //deltaY / 100 表示下拉距离与 100 像素的比值。Math.min() 函数确保这个比值不会超过 1，即pullRatio最大为 1。保持了动画的流畅性
        translateY.value = -40 + (pullRatio * 40); // 更新 translateY 值，限制最小值为-40，最大值为0
    }
    
}
// 触摸结束
async function handleTouchEnd(event){
    endY = event.changedTouches[0].clientY;
    //console.log("结束Y值:",endY)
    
    translateY.value = -40;
    if(isPull.value && ((endY - startY)/100)*20 >= 20 ){
        isPull.value = false;
        isRefreshing.value = true; //模拟"刷新中"

        startY = 0;
        endY = 0;
        setTimeout(async() => {
            await simulateLoading();
            isRefreshing.value = false; //模拟"刷新完成"
        }, 1000);
    }
    else{
        isPull.value = false;
        startY = 0;
        endY = 0;
    }
    contentContainer.value.style.overflow='scroll';
}
//#endregion


onMounted(async() => {
    document.documentElement.scrollTop = 0 //确保刷新的时候滚动到顶部
    newsCategoryArr.value = newsCategoryArr.value.concat(newsStoreObject.newsCategoryInfo)
    await simulateLoading() //获取新闻信息
});

const scrollPosition = ref(0) //记录滚动条位置
onBeforeRouteLeave((to, from, next)=> {
    scrollPosition.value = window.scrollY //跳转路由之前记录滚动条位置
    next(); //允许跳转
})

//当前组件被用keep-alive缓存了，会有两个新的生命周期函数
onActivated(async() => {
    document.body.style.overflow='hidden'
    document.documentElement.scrollTop = scrollPosition.value
    if(userStoreObject.userInfo?.id != null){ //用户登录了
        await getUnreadNotice() //获取未读消息
    }
    //console.log("激活",scrollPosition.value)
});
onDeactivated(() => {
    document.body.style.removeProperty('overflow'); //恢复滚动
    //console.log("离开",scrollPosition.value)
});

</script>


<style lang="scss" scoped>

.category-tags {
    position: fixed;
    top: 64px;
    z-index: 1000;
    display: flex;
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-y: hidden;
    width: 100vw; /* 设置视口宽度，否则position为fixed的盒子无法横向滚动 */
    overflow-x: scroll;
    padding: 8px 0;
    padding-left: 5px;
    margin-bottom: 16px;
    background-color: #ffffff;
}

.category-tag {
    padding: 8px 16px;
    background-color: #f2f2f7;
    border-radius: 16px;
    margin-right: 8px;
    font-size: 14px;
    white-space: nowrap;
}

.contentBox{
    position: relative;
    overflow: scroll;
    scrollbar-width: none;
    -ms-overflow-style: none;
    height: calc(100vh - 210px);
}

.refresh-hint {
    width: 100%;
    position: absolute;
    top: 0;
    // transform: translateY(-20px);
    text-align: center;
    color: #8e8e93;
    font-size: 16px;
}
.pull-hint{
    display: flex;
    justify-content: center;
}


.card {
    background-color: #fff;
    border-radius: 12px;
    overflow: hidden;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.top-bar{
    height: 130px;
}

.list-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eaeaea;
}

.list-item-image {
    width: 80px;
    height: 60px;
    border-radius: 6px;
    object-fit: cover; /* 覆盖图片 */
    
}

.card-title {
    font-size: 16px;
    font-weight: 600;
    // margin-bottom: 8px;
    padding: 10px;
    line-height: 1.3;
}

.card-meta {
    display: flex;
    justify-content: space-between;
    color: #8e8e93;
    font-size: 13px;
    padding: 0 10px 10px 10px;

}

.list-item-title {
    font-size: 16px;
    margin-bottom: 4px;
    padding: 10px;

}

.home-header {
    position: fixed;
    z-index: 1000;
    width: 100%;
    padding: 16px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    border-bottom: 1px solid #eaeaea;
}

.home-logo {
    margin-left: 16px;
    font-size: 22px;
    font-weight: 700;
    color: #007aff;
    display: flex;
    align-items: center;
}

.home-logo i {
    margin-right: 8px;
}

.home-actions {
    display: flex;
    gap: 20px;
    margin-right: 16px;
}

.home-actions i {
    font-size: 20px;
    color: #333;
}

.featured-news {
    margin-bottom: 24px;
}

.section-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 16px;
    padding-left: 16px;
    padding-top: 16px;
}

.news-list {
    margin-top: 16px;
}

.category-tag {
    padding: 8px 16px;
    cursor: pointer;
}

.category-tag.active {
    background-color: #007aff;
    color: #fff;
}


.loading-indicator{
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    // height: 60px;
}
.foot-bar{
    height: 80px;
}
</style>